package com.asa.common.net

import com.asa.common.net.factory.DecodeConverterFactory
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.net.Proxy
import java.util.concurrent.TimeUnit

object ApiManager {

    const val SP_KEY_BASE_URL = "BASE_URL"

    val DEV_URL = "https://www.wanandroid.com/"
//    val PORD_URL = "https://reading-api.qqlszs.com/"



    const val DEFAULT_TIMEOUT = 10*1000L
    private var okHttpClient: OkHttpClient?=null
    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(DEV_URL)
            .addConverterFactory(DecodeConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(getOkHttpClient())
            .build()

    }


    private fun getOkHttpClient():OkHttpClient{
        if (okHttpClient == null){
            okHttpClient = OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT,TimeUnit.MILLISECONDS)
                .proxy(Proxy.NO_PROXY)
                .writeTimeout(DEFAULT_TIMEOUT,TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_TIMEOUT,TimeUnit.MILLISECONDS)
                .addInterceptor(HttpCacheInterceptor())
                .addInterceptor(NetLogInterceptor())
                .build()

        }
        return okHttpClient as OkHttpClient
    }

    fun <T> getApiService(service:Class<T>):T{
        return retrofit.create(service)
    }


}